from __future__ import with_statement

import cgi
from webob import Response
from webob.exc import HTTPMovedPermanently, HTTPTemporaryRedirect
from fusion.http.controllers import BaseController
from fusion.db.profile import Profile
from fusion.db.exceptions import Unauthorized

class Group(BaseController):
    def index(self, req):
        view = self.load_view('group.html')

        if view:
            v = {}
            db = req.environ['fusion.db']

            v['hexlabel'] = req.urlvars['fusion.hexlabel']
            v['my_iid'] = db.get_my_iid()

            gprofile = Profile()
            gprofile.read(db, v['hexlabel'])
            v['profile_fields'] = self._process_group_profile(db, gprofile, v['hexlabel'])

            v['member_list'] = self._process_member_list(db, v['hexlabel'], v['my_iid'])
            
            v['is_member'] = v['my_iid'] in v['member_list']['index']
            v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

            # make it so
            return view.render(**v)
        else:
            return None


    def edit_picture(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['fusion.db']

            v['hexlabel'] = req.urlvars['fusion.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['member_list'] = self._process_member_list(db, v['hexlabel'], v['my_iid'])
            
            v['is_member'] = v['my_iid'] in v['member_list']['index']
            v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

            # get raw profile obj
            #g = db.get_view(v['hexlabel'])
            gprofile = Profile()
            gprofile.read(db, v['hexlabel'])


            if req.POST.has_key('do'):
                if req.POST['do'] == 'delete':
                    # delete picture
                    gprofile.pic = None

            if req.POST.has_key('generic#0#picture'):
                # save new picture
                upload = req.POST['generic#0#picture']
                if upload.__class__ == cgi.FieldStorage:
                    with upload.file as f:
                        newpic = f.read()

                    gprofile.pic = newpic

            # write profile
            try:
                gprofile.write(db, v['hexlabel'])
            except (Unauthorized, LookupError):
                #[FIXME: should something happen here?]
                pass

            # redirect to profile
            redir_url = '/group/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('group.edit_picture.html')

            if view:
                v = {}
                db = req.environ['fusion.db']

                v['hexlabel'] = req.urlvars['fusion.hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['member_list'] = self._process_member_list(db, v['hexlabel'], v['my_iid'])
                
                v['is_member'] = v['my_iid'] in v['member_list']['index']
                v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

                # get raw profile obj
                gprofile = Profile()
                gprofile.read(db, v['hexlabel'])

                v['profile_fields'] = self._process_group_profile(db, gprofile, v['hexlabel'])

                # engage -->
                return view.render(**v)
            else:
                return None

    def edit(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['fusion.db']

            v['hexlabel'] = req.urlvars['fusion.hexlabel']
            v['is_self']  = db.get_my_iid() == v['hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['member_list'] = self._process_member_list(db, v['hexlabel'], v['my_iid'])
            v['is_member'] = v['my_iid'] in v['member_list']['index']
            v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

            # get raw profile obj
            profile = Profile()
            profile.read(db, v['hexlabel'])

            # get the generic fields
            generic_fields = set([(key,val) for key,val in req.POST.items() if key.startswith('generic')])

            #[TODO: convert to dictionaries no good?]
            generic_fields = dict(generic_fields)

            # clear existing fields (doesn't affect picture)
            profile.clear_all_fields()

            # update name
            name = (generic_fields['generic#0#name'] or '').strip()
            if name:
                profile.name = name

            # update about
            profile.set_about(generic_fields['generic#0#about'] or '', public=True)

            # write profile
            try:
                profile.write(db, v['hexlabel'])
            except (Unauthorized, LookupError):
                #[FIXME: should something happen here?]
                pass

            # redirect to profile
            redir_url = '/group/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('group.edit.html')

            if view:
                v = {}
                db = req.environ['fusion.db']

                v['hexlabel'] = req.urlvars['fusion.hexlabel']
                v['is_self']  = db.get_my_iid() == v['hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['member_list'] = self._process_member_list(db, v['hexlabel'], v['my_iid'])
                v['is_member'] = v['my_iid'] in v['member_list']['index']
                v['is_admin'] = v['is_member'] and 'admin' in v['member_list']['items'][v['my_iid']]['roles']

                # get raw profile obj
                gprofile = Profile()
                gprofile.read(db, v['hexlabel'])
                v['profile'] = gprofile
                
                v['profile_fields'] = self._process_group_profile(db, gprofile, v['hexlabel'])

                # engage -->
                return view.render(**v)
            else:
                return None

